package data

import (
	"context"
	"verify-code/internal/conf"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/wire"
	"github.com/redis/go-redis/v9"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewGreeterRepo, NewCustomerData)

// Data .
type Data struct {
	// TODO wrapped database client
	Rdb *redis.Client
}

// NewData .
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
	// 初始化 Rdb
	data := &Data{}

	options := &redis.Options{
		Addr:         c.Redis.Addr,
		Password:     c.Redis.Password,
		DB:           0,
		ReadTimeout:  c.Redis.ReadTimeout.AsDuration(),
		WriteTimeout: c.Redis.WriteTimeout.AsDuration(),
	}

	//连接redis
	//redisURL := fmt.Sprintf("redis://%s/0?dial_timeout=%d", c.Redis.Addr, 1)
	//options, err := redis.ParseURL(redisURL)
	//if err != nil {
	//	data.Rdb = nil
	//}

	data.Rdb = redis.NewClient(options)

	if err := data.Rdb.Ping(context.Background()).Err(); err != nil {
		return nil, nil, err
	}

	cleanup := func() {
		log.NewHelper(logger).Info("closing the data resources")
	}
	return data, cleanup, nil
}
